package com.example.dql.diary.Http;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by dql on 2018/3/1.
 */

public class HttpRequest {

    private Handler handler;
    private Context context;

    public HttpRequest(Handler handler, Context context){
        this.handler = handler;
        this.context = context;
    }

    public void doPost(final String url,final int what, String tag, final Map<String,String> paramsMap){
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : paramsMap.keySet()) {
            builder.add(key, paramsMap.get(key));
        }
        final Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message msg = handler.obtainMessage();
                msg.what = what;
                msg.arg1 = -1;
                handler.sendMessage(msg);
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
//               Log.e("onResponse: ",response.body().string() );
                Message msg = handler.obtainMessage();
                msg.what = what;
                msg.obj = response.body().string().trim();
                handler.sendMessage(msg);
            }
        });
    }
}
